<template>
    <div class="global-search-container">
        <el-form :inline="true" ref="form" class="global-search" :model="form">
            <el-form-item label="机构">
                <el-select v-model="form.orgId" filterable class="mechanism" @change="setDepartmentList" size="small" placeholder="请选择">
                    <el-option
                        v-for="item in orgList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="出院科室" v-show="showDep">
                <el-cascader
                    v-show="!isNoKnowDep"
                    ref="cascaderSelector"
                    :key="isResouceShow"
                    class="dep-select"
                    v-model="form.dep"
                    :show-all-levels="false"
                    :options="departmentList"
                    :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
                    filterable
                    @change="setDoctorList"
                    size="small">
                </el-cascader>
                <span v-show="isNoKnowDep" class="noKnowDep">未知科室</span>
            </el-form-item>
            <el-form-item label="编码员" v-show="showCoder">
                <el-select v-model="form.coder" filterable class="coder" size="small" placeholder="请选择">
                    <el-option v-if="coderList.length > 0 && !noAllCoder" key="0" label="全部" value="0"></el-option>
                    <el-option
                        v-for="item in coderList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="住院医师" v-show="showDoctor">
                <el-select v-model="form.resident" filterable class="coder" size="small" placeholder="请选择">
                    <el-option v-if="doctorList.length > 0 && !noAllDoctor" key="0" label="全部" value="0"></el-option>
                    <el-option
                        v-for="item in doctorList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item :label="showDep ? '出院时间' : '上传时间'" class="time-select-form-box" v-show="showTime">
                <el-select v-model="form.timeUnit" class="time-unit" size="small" placeholder="">
                    <el-option label="年" value="year"></el-option>
                    <el-option label="季度" value="quarter"></el-option>
                    <el-option label="月" value="month"></el-option>
                </el-select>
                <select-year v-show="form.timeUnit !== 'month'" @selectYear="selectYear" :yearMonth="form.yearMonth" />
                <el-date-picker
                    v-show="form.timeUnit === 'month'"
                    class="year-month"
                    size="small"
                    v-model="form.yearMonth"
                    :type="form.timeUnit === 'month' ? 'month' : 'year'"
                    value-format="yyyy-MM-dd"
                    popper-class="custom-date-width"
                    :clearable="false">
                </el-date-picker>
                <el-select v-if="form.timeUnit === 'quarter'" class="quarter" size="small" v-model="form.quarter" placeholder="">
                    <el-option label="第一季度" value="1"></el-option>
                    <el-option label="第二季度" value="2"></el-option>
                    <el-option label="第三季度" value="3"></el-option>
                    <el-option label="第四季度" value="4"></el-option>
                </el-select>
            </el-form-item>
            <slot name="other-form"></slot>
            <el-form-item>
                <el-button class="sub-btn" type="primary" size="small" @click="onSubmit">查询</el-button>
            </el-form-item>
        </el-form>
        <div>
            <el-radio style="margin-right: 10px;" v-model="form.isLast" :label="false" @change="onSubmit" v-if="!isDataPackge && isShowLast && showLast">首次</el-radio>
            <el-radio v-model="form.isLast" :label="true" @change="onSubmit" v-if="!isDataPackge && isShowLast && showLast">末次</el-radio>
        </div>
    </div>
</template>

<script>
    import { getCoderList, getDoctorList } from '@/api/global/index'
    import SelectYear from '@/components/SelectYear'
    import {Bus} from '@/utils/bus'

    export default {
        name: 'GlobalSearch',
        props: {
            // 显示科室
            showDep: {
                type: Boolean,
                default: true
            },
            // 显示编码员
            showCoder: {
                type: Boolean,
                default: false
            },
            // 显示住院医师
            showDoctor: {
                type: Boolean,
                default: false
            },
            // 显示末次统计
            showLast: {
                type: Boolean,
                default: true
            },
            // 显示时间
            showTime: {
                type: Boolean,
                default: true
            }
        },
        data () {
            return {
                // 搜索框
                form: {
                    orgId: '',
                    dep: '',
                    timeUnit: 'year',
                    yearMonth: '',
                    quarter: '1',
                    coder: '',
                    isLast: true
                },
                // 全局使用到的内容
                globalForm: {
                    orgId: '',
                    // 科别
                    department: '',
                    // 科室名
                    departmentName: '',
                    start: '',
                    end: '',
                    isLast: true
                },
                // 机构列表
                orgList: [],
                // 出院科室列表
                departmentList: [],
                // 编码员列表
                coderList: [],
                // 医师列表
                doctorList: [],
                // cascader的key值，避免组件报错
                isResouceShow: 0,
                // 当前是数据管理页面病案包
                isDataPackge: false,
                // 是否显示末次统计
                isShowLast: true,
                // 参数配置查看病案时间
                viewDeadlineDays: '',
                // 是未知科室
                isNoKnowDep: false,
                // 未知科室名称
                noKnowDepName: '',
                // 未知科室编码
                noKnowDepCode: '',
                // 没有全部编码员
                noAllCoder: false,
                // 没有全部医师
                noAllDoctor: false
            }
        },
        created () {
            this.initData()
            this.setDepartmentList(this.form.orgId, this.form.dep, 'isInit')
            if (this.$route.name === 'DoctorSummaryAnalysisIndex') {
                this.noAllDoctor = true
            } else if (this.$route.name === 'CoderSummaryAnalysisIndex') {
                this.noAllCoder = true
            }
            if (this.$route.name !== 'ScoreOverview') this.onSubmit()
        },
        mounted () {
            if (this.$route.name === 'ScoreOverview') this.onSubmit()
        },
        methods: {
            /**
             * 初始数据获取
             */
            initData () {
                this.orgList = this.getLocalStorage('userInfo', 'mechanism')
                // 因为orgId是必选的，所以依靠这个来判断是否有页面独立的搜索条件
                let query = this.$store.state.search.searchForm[this.$route.name]
                if (query.orgId) {
                    this.form = {
                        orgId: query.orgId,
                        dep: this.setDepId(query.orgId, query.department, query.departmentName),
                        timeUnit: query.timeUnit,
                        yearMonth: query.yearMonth,
                        quarter: query.quarter,
                        coder: query.coder,
                        resident: query.resident,
                        isLast: query.isLast
                    }
                    this.globalForm = {
                        orgId: query.orgId,
                        department: query.department,
                        departmentName: query.departmentName,
                        start: query.start,
                        end: query.end,
                        coder: query.coder,
                        resident: query.resident,
                        isLast: query.isLast
                    }
                    if (query.start === '1970-01-01 00:00:00') {
                        this.form.yearMonth = ''
                    }
                    // 判断是否有保存的最新筛选参数
                } else if (localStorage.getItem('globalSearchQC')) {
                    this.form = JSON.parse(localStorage.getItem('globalSearchQC'))
                    this.globalForm = JSON.parse(localStorage.getItem('globalFormQC'))
                    // 保存当前页面参数(筛选参数和表单参数一起)
                    this.setGetStore(this.$route.name, this.form, this.globalForm)
                } else {
                    // 第一次进入
                    let date = new Date()
                    this.form.yearMonth = `${date.getFullYear()}-${date.getMonth() + 1}-01`
                    this.setMechanismId()
                }
            },
            /**
             * 查找科室id
             * @param orgId 机构id
             * @param depCode 科室类别
             * @param depName 科室名称
             */
            setDepId (orgId, depCode, depName) {
                if (!depCode) return ''
                let res = ''
                let orgList = this.getLocalStorage('userInfo', 'mechanism')
                orgList.forEach(item => {
                    if (item.id === orgId && item.organDep && item.organDep.length && !res) {
                        res = this.findDepId(item.organDep, depCode, depName)
                    }
                })
                if (!res && depCode && depName) {
                    let query = this.$store.state.search.searchForm[this.$route.name]
                    this.isNoKnowDep = true
                    this.noKnowDepName = query.departmentName
                    this.noKnowDepCode = query.department
                }
                return res
            },
            /**
             * 查找科室id
             * @param list 科室列表
             * @param code 科室类别
             * @param name 科室名称
             */
            findDepId (list, code, name) {
                let res = ''
                list.forEach(item => {
                    if ((item.code === code || item.code.split('.')[0] === code) && item.name === name) {
                        res = item.id
                    } else if (item.children && item.children.length && !res) {
                        res = this.findDepId(item.children, code, name)
                    }
                })
                return res
            },
            /**
             * 设置机构id
             */
            setMechanismId () {
                if (this.orgList.length) {
                    if (this.getLocalStorage('userMechanism', 'id') && this.hasMechanismId(this.getLocalStorage('userMechanism', 'id'))) {
                        this.form.orgId = this.getLocalStorage('userMechanism', 'id')
                    } else {
                        this.form.orgId = this.orgList[0].id
                    }
                }
            },
            /**
             * 判断所属机构是否在组织机构中
             * @param id 所属机构id
             */
            hasMechanismId (id) {
                let res = this.orgList.filter(item => item.id === id)
                return res.length !== 0
            },
            /**
             * 选择年
             * @param data 选择的数据
             */
            selectYear (data) {
                this.form.yearMonth = data
            },
            /**
             * 选择机构后设置出院科室内容
             * @param val 选中的id
             * @param department 科室id
             * @param isInit 是否是初始化
             */
            setDepartmentList (val, department, isInit) {
                this.isResouceShow++
                this.form.dep = ''
                this.departmentList = []
                let checkAuth = Number(this.getLocalStorage('userInfo', 'checkAuth'))
                let index = this.orgList.findIndex(item => item.id === val)
                let departmentList = []
                if (this.orgList.length) {
                    departmentList = this.orgList[index].organDep
                    this.viewDeadlineDays = this.orgList[index].viewDeadlineDays
                    if (departmentList.length && checkAuth !== 1 && checkAuth !== 2 && departmentList[0].id !== '0') {
                        if (this.$route.name !== 'DepSummaryAnalysisIndex' && this.$route.name !== 'DoctorSummaryAnalysisIndex') {
                            departmentList.unshift({
                                id: '0',
                                name: '全院'
                            })
                        }
                    }
                }
                this.departmentList = departmentList
                // 判断的是'' 和 undefined
                if (department) {
                    this.form.dep = department
                } else if (departmentList.length && (checkAuth === 1 || checkAuth === 2)) {
                    this.form.dep = departmentList[0].id
                } else {
                    this.form.dep = departmentList.length ? '0' : ''
                }
                if (this.$route.query.department && this.form.dep === '0') {
                    this.form.dep = ''
                }
                if (this.isNoKnowDep && !isInit) {
                    this.isNoKnowDep = false
                    this.noKnowDepName = ''
                    this.noKnowDepCode = ''
                }
                this.getCoder(val)
                this.getDoctor(val, '')
            },
            /**
             * 获取编码员
             * @param val 机构id
             */
            getCoder (val) {
                this.coderList = []
                let params = {
                    orgId: val
                }
                // 请求编码员列表
                getCoderList(params).then(res => {
                    if (res.code.toString() === '200') {
                        if (res.data) {
                            let coderList = []
                            res.data.forEach((item, index) => {
                                if (item && item !== '') {
                                    coderList.push({
                                        value: index + 1,
                                        label: item
                                    })
                                }
                            })
                            this.coderList = coderList
                            if (!this.coderList.length) {
                                this.form.coder = ''
                            }
                            this.$emit('changeCoderList', coderList)
                        }
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            /**
             * 修改科室后
             */
            setDoctorList () {
                this.getDoctor(this.form.orgId, this.form.dep === '0' ? '' : this.form.dep)
            },
            /**
             * 获取住院医师
             * @param val 机构id
             * @param depCode 科室编码
             */
            getDoctor (val, depCode) {
                this.doctorList = []
                let params = {
                    orgId: val,
                    department: depCode
                }
                // 请求住院医师列表
                getDoctorList(params).then(res => {
                    if (res.code.toString() === '200') {
                        if (res.data) {
                            let doctList = []
                            res.data.forEach((item, index) => {
                                if (item && item !== '') {
                                    doctList.push({
                                        value: index + 1,
                                        label: item
                                    })
                                }
                            })
                            this.doctorList = doctList
                            if (!this.doctorList.length) {
                                this.form.resident = ''
                            }
                            this.$emit('changeDoctorList', doctList)
                        }
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            /**
             * 获取对应科室
             * @param arr 科室集合
             * @param id 查询的科室id
             */
            getDepCode (arr, id) {
                let res = []
                if (arr && !res.length) {
                    arr.forEach(item => {
                        if (item.id === id && !res.length) {
                            res.push(item)
                        } else if (item.children && !res.length) {
                            res = this.getDepCode(item.children, id)
                        }
                    })
                }
                return res
            },
            onSubmit () {
                this.globalForm.isLast = this.form.isLast
                this.globalForm.orgId = this.form.orgId
                this.globalForm.coder = this.form.coder === '0' ? '' : this.form.coder
                this.globalForm.resident = this.form.resident === '0' ? '' : this.form.resident
                // 判断是否有科室选中
                if (this.form.dep === '' || this.form.dep === '0') {
                    this.globalForm.department = ''
                    this.globalForm.departmentName = ''
                } else {
                    let depItem = this.getDepCode(this.departmentList, this.form.dep)
                    this.globalForm.department = depItem[0] ? depItem[0].code : ''
                    this.globalForm.departmentName = depItem[0] ? depItem[0].name : ''
                }
                // 获取对应时间选择器时间
                this.globalForm = this.getPickerTime(this.globalForm)
                // 保存当前页面参数(筛选参数和表单参数一起)
                this.setGetStore(this.$route.name, this.form, this.globalForm)
                // 保存最新筛选参数
                if (this.$route.meta && !this.$route.meta.independent) {
                    localStorage.setItem('globalSearchQC', JSON.stringify(this.form))
                    localStorage.setItem('globalFormQC', JSON.stringify(this.globalForm))
                    localStorage.setItem('viewDeadlineDays', this.viewDeadlineDays)
                }
                if (this.isNoKnowDep) {
                    this.globalForm.departmentName = this.noKnowDepName
                    this.globalForm.department = this.noKnowDepCode
                }
                this.$emit('submitSearch', this.globalForm)
                Bus.$emit('globalGetTotal', this.form.orgId)
            },
            /**
             * 获取时间
             * @param params 参数对象
             */
            getPickerTime (params) {
                if (!this.form.yearMonth) {
                    params.start = '1970-01-01'
                    params.end = '2070-12-31'
                    return params
                }
                let time = this.form.yearMonth
                let timeArr = time.split('-')
                let year = timeArr[0]
                let month = timeArr[1]
                // 每月天数
                let d = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
                if (this.form.timeUnit === 'month') {
                    params.start = time
                    // 判断闰年二月
                    if (parseInt(month) === 2 && year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
                        params.end = `${year}-${month}-${d[parseInt(month) - 1] + 1}`
                    } else {
                        params.end = `${year}-${month}-${d[parseInt(month) - 1]}`
                    }
                } else if (this.form.timeUnit === 'quarter') {
                    // 判断季度
                    switch (this.form.quarter) {
                    case '1':
                        params.start = `${year}-01-01`
                        params.end = `${year}-03-31`
                        break
                    case '2':
                        params.start = `${year}-04-01`
                        params.end = `${year}-06-30`
                        break
                    case '3':
                        params.start = `${year}-07-01`
                        params.end = `${year}-09-30`
                        break
                    case '4':
                        params.start = `${year}-10-01`
                        params.end = `${year}-12-31`
                        break
                    }
                } else if (this.form.timeUnit === 'year') {
                    params.start = `${year}-01-01`
                    params.end = `${year}-12-31`
                }
                return params
            }
        },
        components: {
            SelectYear
        }
    }
</script>

<style scoped lang="scss">
    .global-search-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 3px;
        margin-bottom: 10px;
        .el-form-item {
            margin-bottom: 0;
        }
        .mechanism {
            width: 120px;
        }
        .dep-select {
            width: 120px;
        }
        .time-unit {
            width: 75px;
        }
        .coder {
            width: 120px;
        }
        /deep/.year-month {
            width: 120px;
        }
        .quarter {
            width: 100px;
        }
        .noKnowDep {
            font-size: 14px;
            color: #606266;
            margin-right: 4px;
        }
        .tool-box {
            button {
                padding: 0;
                height: 28px;
                line-height: 28px;
                font-size: 14px;
            }
        }
        .time-select-form-box {
            /deep/.el-form-item__content {
                height: 40px;
                & > div {
                    float: left;
                }
            }
        }
    }
</style>
